package org.zy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class RealSocket {
    static EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    /**
     * 连接真实服务
     *
     * @param visitorId 访客ID
     * @return
     */
    public static Channel connectRealServer(String visitorId) {
        if (visitorId == null || visitorId.length() == 0) {
            return null;
        }

        Channel channel = ClientChannelManager.REAL_CHANNEL_MAP.get(visitorId);
        if (null == channel) {
            newConnect(visitorId);
            channel = ClientChannelManager.REAL_CHANNEL_MAP.get(visitorId);
        }
        return channel;
    }

    private static void newConnect(String visitorId) {
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new RealHandler());
                        }
                    });

            bootstrap.connect(Config.realIp, Config.realPort).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // 客户端链接真实服务成功
                        future.channel().config().setOption(ChannelOption.AUTO_READ, false);
                        future.channel().attr(ClientChannelManager.VISITOR_ID).set(visitorId);
                        ClientChannelManager.REAL_CHANNEL_MAP.put(visitorId, future.channel());
                        ProxySocket.connectProxyServer(visitorId);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}